package com.dailyblue.java.spring.cloud.example.customer.basic.service.impl;

import com.dailyblue.java.spring.cloud.example.customer.basic.service.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class CustomerServiceImpl implements CustomerService {

    // 引入发现
    @Resource
    private DiscoveryClient discoveryClient;
    @Resource
    private RestTemplate restTemplate;

    @Override
    public String a() {
        // 发现example-producer服务的提供者
        List<ServiceInstance> list = discoveryClient.getInstances("example-producer");
        // 就像获取其中一个
        ServiceInstance instance = list.get(0);
        String uri = instance.getUri().toString() + "/producer/a";
        log.info("发现了服务:{},路径是:{}", list, uri);
        String result = restTemplate.getForObject(uri, String.class);
        log.info("获取的结果是:{}", result);
        return result;
    }

    private int i = 0;

    @Override
    public String b() {
        List<ServiceInstance> list = discoveryClient.getInstances("example-producer");
        ServiceInstance instance = list.get(i);
        if (i < list.size() - 1) {
            i++;
        } else {
            i = 0;
        }
        String uri = instance.getUri().toString() + "/producer/a";
        return restTemplate.getForObject(uri, String.class);
    }

    @Override
    public String c() {
        List<ServiceInstance> list = discoveryClient.getInstances("example-producer");
        int j = (int) (Math.random() * list.size());
        ServiceInstance instance = list.get(j);
        String uri = instance.getUri().toString() + "/producer/a";
        return restTemplate.getForObject(uri, String.class);
    }

    // ribbon 方式，自带负载均衡
    public String d() {
        String uri = "http://example-producer/producer/a";
        return restTemplate.getForObject(uri, String.class);
    }
}
